import { Component, OnInit } from '@angular/core';
import { NbWindowRef, NbWindowService } from '@nebular/theme';
import { CheckWeekdayComponent } from '../check-weekday/check-weekday.component';
import { HttpHelper } from '../../Helper/HttpHelper';
import { DtoResultObj } from 'src/app/Model/DtoRec/DtoResult';
import { LocalDataSource } from 'src/app/Lib/ng2-smart-table/public-api';
import { DtoSaveObj } from 'src/app/Model/DtoPost/DtoSaveObj';
import { Fun } from 'src/app/Config/Fun';

@Component({
  selector: 'app-course-cfg',
  templateUrl: './course-cfg.component.html'
})
export class CourseCfgComponent implements OnInit {
  buttons = []
  bean = {
    "classes_cfg_id": 0,
    "classes_id": 0,
    "years": 0,
    "num": 0,
    "create_time": 0,
    "no_course": "",
    "TeacherCfgList": [
      {
        "teacher_name": "",
        "classesId1": 0,
        "classesId2": 0,
        "classesId3": 0,
        "classesId4": 0,
        "classesId5": 0,
        "classesId6": 0,
        "teacher_cfg_id": 0,
        "classes_cfg_id": 0,
        "teacher_course_id": 0,
        "week_num": 0,
        "is_use": 0,
        "ClassesIdList": [
          0
        ]
      }
    ],
  }
  screenheight: number = document.documentElement.clientHeight - 300
  screenWidth: number = document.documentElement.clientWidth * 0.8
  teacherList: any[] = [];
  classesList: any[] = [];

  //用于加载设置，如果为 false，则不显示Table,
  LoadSetting: boolean = false;
  settings = {
    noDataMessage: "无数据",
    mode: "inline",
    selectMode: 'single', // single|multi
    // hideHeader: true,
    hideSubHeader: true, //隐藏筛选行
    actions: {
      columnTitle: "操作",
      add: false,
      delete: false,
      position: 'left'
      // position:"right"
    },
    add: {
      addButtonContent: '添加',
      createButtonContent: '创建',
      cancelButtonContent: '取消',
    },
    edit: {
      editButtonContent: '编辑',
      saveButtonContent: '确定',
      cancelButtonContent: '取消',
    },
    delete: {
      deleteButtonContent: '删除',
      confirmDelete: true,
    },
    columns: {
      teacher_name: {
        title: '科目',
        type: 'number',
        editable: false
      },
      week_num: {
        title: '每周节数',
        type: 'string',
      },
      classesId1: {
        title: '合班1',
        type: 'text',
        editable: false,
        valuePrepareFunction: (v) => { return this.formartClassesName(v) },
        editor: {
          type: "list",
          config: {
            list: []
          }
        }
      },
      classesId2: {
        title: '合班2',
        type: 'text',
        valuePrepareFunction: (v) => { return this.formartClassesName(v) },
        editor: {
          type: "list",
          config: {
            list: []
          }
        }
      },
      classesId3: {
        title: '合班3',
        type: 'text',
        valuePrepareFunction: (v) => { return this.formartClassesName(v) },
        editor: {
          type: "list",
          config: {
            list: []
          }
        }
      },
      classesId4: {
        title: '合班4',
        type: 'text',
        valuePrepareFunction: (v) => { return this.formartClassesName(v) },
        editor: {
          type: "list",
          config: {
            list: []
          }
        }
      },
      classesId5: {
        title: '合班5',
        type: 'text',
        valuePrepareFunction: (v) => { return this.formartClassesName(v) },
        editor: {
          type: "list",
          config: {
            list: []
          }
        }
      },
      classesId6: {
        title: '合班6',
        type: 'text',
        valuePrepareFunction: (v) => { return this.formartClassesName(v) },
        editor: {
          type: "list",
          config: {
            list: []
          }
        }
      }
      
    },
  };

  courseList: any = {};
  //星期
  weekDay: any = {};

  source: LocalDataSource = new LocalDataSource();
  constructor(
    private windowService: NbWindowService,
    public windowRef: NbWindowRef,
    private HttpHelper: HttpHelper,
  ) {
    // this.bean=this.windowRef.config.context;
  }

  formartClassesName(id) {
    if (this.classesList != null) {
      for (let index = 0; index < this.classesList.length; index++) {
        const element = this.classesList[index];
        if (element.value == id) {
          return element.title;
        }
      }
    }
    return id;
  }

  ngOnInit(): void {
    //从query传过来的实体
    console.log(this.bean)
    if (this.bean.no_course != null && this.bean.no_course != "") {
      this.bean.no_course.split(',').forEach(element => {
        this.weekDay["key_" + element] = true;
      });
    }



    this.HttpHelper.Post("Public/ClassesList", null).then((data: DtoResultObj<any>) => {
      if (data.success) {
        this.classesList = [{ value: "", title: "" }];
        data.dataList.forEach(element => {
          this.classesList.push({ value: parseInt(element.id), title: element.name })
        });
        this.settings.columns.classesId1.editor.config.list = this.classesList;
        this.settings.columns.classesId2.editor.config.list = this.classesList;
        this.settings.columns.classesId3.editor.config.list = this.classesList;
        this.settings.columns.classesId4.editor.config.list = this.classesList;
        this.settings.columns.classesId5.editor.config.list = this.classesList;
        this.settings.columns.classesId6.editor.config.list = this.classesList;
        this.LoadSetting = true;
      }
    }, (x) => {
      console.log(x)
    })

    this.HttpHelper.Post("Public/TeacherCourseList", null).then((data: DtoResultObj<any>) => {
      if (data.success) {
        this.teacherList = data.dataList;
        console.log(this.teacherList)
        // 配置选择，以及设置显示教师名
        this.teacherList.forEach(element => {
          this.courseList["key_" + element.id] = false;
          this.bean.TeacherCfgList.forEach(cfgList => {
            if (cfgList.teacher_course_id == element.id) {
              cfgList.teacher_name = element.name;
            }
          });
        });

        if (this.bean.TeacherCfgList == null) {
          this.bean.TeacherCfgList = [];
        }
        this.bean.TeacherCfgList.forEach(element => {
          this.courseList["key_" + element.teacher_course_id] = true;
        });


        this.bean.TeacherCfgList.forEach(element => {
          element.classesId1 = 0;
          for (let index = 0; index < element.ClassesIdList.length; index++) {
            const tmp = element.ClassesIdList[index];
            if (tmp == this.bean.classes_id) {
              element.classesId1 = tmp;
            } else {
              if (element.classesId1 == 0) {
                eval("element.classesId" + (index + 2) + "=" + tmp);
              }
              else {
                eval("element.classesId" + (index + 1) + "=" + tmp);
              }
            }

          }

        });
        console.log(this.bean);
      }
    }, (x) => {
      console.log(x)
    })

  }


  checkNoCourse() {
    this.windowService.open(CheckWeekdayComponent, {
      closeOnBackdropClick: false,
      windowClass: "DivWindow",
      title: "选择",
      context: {
        buttons: [
          {
            name: "确定", click: (x) => {
              return new Promise(async (resolve, reject) => {
                console.log(x);
                resolve({});
              });
            }
          }]
      }
    });
  }

  ButtonClick(even) {

    let list = [];
    for (const key in this.weekDay) {
      const element = this.weekDay[key];
      if (this.weekDay[key]) {
        list.push(key.replace("key_", ""));
      }
    }
    this.bean.no_course = list.join(",");
    this.bean.TeacherCfgList.forEach(element => {
      element.ClassesIdList = [];
      if (element.classesId1)
        element.ClassesIdList.push(element.classesId1)

      if (element.classesId2)
        element.ClassesIdList.push(element.classesId2)

      if (element.classesId3)
        element.ClassesIdList.push(element.classesId3)

      if (element.classesId4)
        element.ClassesIdList.push(element.classesId4)

      if (element.classesId5)
        element.ClassesIdList.push(element.classesId5)

      if (element.classesId6)
        element.ClassesIdList.push(element.classesId6)
    });

    even(Fun.ClearNull(this.bean))
      .then((x: DtoResultObj<any>) => {
        console.log(x)
        if (x.success) {
          this.windowRef.close();
        }
      })
  }

  changeTab($event: any) {
    if ($event.tabId == 3) {
      if (this.bean.TeacherCfgList == null) this.bean.TeacherCfgList = [];
      //删除不存在的
      for (let index = 0; index < this.bean.TeacherCfgList.length; index++) {
        const element = this.bean.TeacherCfgList[index];
        let isexist = false;

        for (const key in this.courseList) {
          if (this.courseList[key]) {
            let id = parseInt(key.replace("key_", ""));
            if (element.teacher_course_id == id) {
              isexist = true;
              break;
            }
          }
        }
        if (!isexist) {
          this.bean.TeacherCfgList.splice(index, 1);
          console.log(this.bean.TeacherCfgList);
        }
      }

      //添加选中的
      for (const key in this.courseList) {
        if (this.courseList[key]) {
          let id = parseInt(key.replace("key_", ""));
          let isexist = false;
          for (let index = 0; index < this.bean.TeacherCfgList.length; index++) {
            const element = this.bean.TeacherCfgList[index];
            if (element.teacher_course_id == id) {
              isexist = true;
              break;
            }
          }
          if (!isexist) {
            let teacherName = "";
            this.teacherList.forEach(element => {
              if (element.id == id) teacherName = element.name;
            });
            this.bean.TeacherCfgList.push({
              "teacher_name": teacherName,
              "classesId1": this.bean.classes_id,
              "classesId2": 0,
              "classesId3": 0,
              "classesId4": 0,
              "classesId5": 0,
              "classesId6": 0,
              "teacher_cfg_id": 0,
              "classes_cfg_id": 0,
              "teacher_course_id": id,
              "week_num": 0,
              "is_use": 1,
              "ClassesIdList": [
                0
              ]
            })
          }
        }
      }

      this.source.load(this.bean.TeacherCfgList);
    }
  }

}
